package com.silence.whereeat.dao;

import com.silence.whereeat.model.UserStore;
import com.silence.whereeat.service.UserStoreService;
import com.silence.whereeat.utils.DBUtils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 商店评论
 * Created by 伟阳 on 2015/9/14.
 */
public class UserStoreDao implements UserStoreService {

    private DBUtils dbUtils;

    public UserStoreDao() {
        dbUtils = new DBUtils();
    }

    public int commentStore(UserStore userStore) {
        String sql = "INSERT INTO user_store VALUES (?,?,?,?);";
        List<Object> list = new ArrayList<Object>();
        list.add(userStore.getUser_id());
        list.add(userStore.getStore_id());
        list.add(userStore.getStar());
        list.add(userStore.getComment());
        int result = -1;
        try {
            result = dbUtils.updateByPreParedStatement(sql, list);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    public double getAverageStar(int storeId) {
        String sql = "SELECT AVG(star) AS avg FROM user_store WHERE store_id=?;";
        List<Object> list = new ArrayList<Object>();
        list.add(storeId);
        double result = -1;
        try {
            result = Double.parseDouble(dbUtils.querySingleResult(sql, list).get("avg").toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    public void close() {
        dbUtils.close();
    }

    public List<UserStore> getComments(int passage) {
        String sql = "SELECT * " +
                "FROM user_store " +
                "LIMIT ?,?;";
        List<Object> list = new ArrayList<Object>();
        list.add(passage * 10);
        list.add(passage * 10 + 9);
        List<UserStore> comments = null;
        try {
            comments = dbUtils.queryResultSet(sql, list, UserStore.class);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            dbUtils.close();
        }
        return comments;
    }
}
